package com.feng.security.service.impl;

import cn.hutool.captcha.GifCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.dto.LoginDto;
import com.feng.common.exceptions.PathException;
import com.feng.common.exceptions.ServiceException;
import com.feng.common.utils.SecurityUtil;
import com.feng.common.vo.ApiRest;
import com.feng.security.entity.User;
import com.feng.security.mapper.UserMapper;
import com.feng.security.service.UserService;
import com.feng.security.utils.JwtUtils;
import com.feng.security.utils.RsaUtils;
import com.feng.security.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author feng
 * @since 2023-03-21 09:22:39
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public ApiRest login(LoginDto loginDto) {
        GifCaptcha gif = SecurityUtil.gif;
        if (loginDto == null) {
            throw new ServiceException("请输入完整信息");
        }
        if (!gif.verify(loginDto.getCode())) {
            throw new ServiceException("验证码错误");
        }
        if (loginDto.getUsername() == null) {
            throw new ServiceException("请输入用户名");
        }
        if (loginDto.getPassword() == null) {
            throw new ServiceException("请输入密码");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserName, loginDto.getUsername());
        User user = baseMapper.selectOne(queryWrapper);
        boolean loginFlag = encoder.matches(loginDto.getPassword(), user.getPassword());
        if (!loginFlag) {
            return ApiRest.failure("用户名或密码错误", null);
        }
        //查询用户权限
        UserVO power = baseMapper.findPower(user.getUserId().toString());
        //消除敏感信息
        user.setPassword(null);
        power.setUser(user);
        //返回token
        PrivateKey privateKey;
        try {
            byte[] bytes = RsaUtils.readByByte(new ClassPathResource("key/pri").getInputStream());
            privateKey = RsaUtils.getPrivateKey(bytes);
        } catch (Exception e) {
            throw new PathException("服务器繁忙");
        }
        String token = JwtUtils.generateTokenExpireInMinutes(power, privateKey, 60 * 24);//令牌一天过期
        return ApiRest.success("登陆成功", token);
    }

    @Override
    public ApiRest pathPower(String token) {
        PublicKey publicKey = null;
        try {
            byte[] bytes = RsaUtils.readByByte(new ClassPathResource("key/pub").getInputStream());
            publicKey = RsaUtils.getPublicKey(bytes);
        } catch (Exception e) {
            throw new PathException("服务器繁忙");
        }
        JwtUtils.getInfoFromToken(token, publicKey, UserVO.class);
        return ApiRest.success("令牌校验成功", null);
    }
}
